package com.tpp.threat_perception_platform.permission;

import com.tpp.threat_perception_platform.dao.RoleMapper;
import com.tpp.threat_perception_platform.dao.UserMapper;
import com.tpp.threat_perception_platform.pojo.Role;
import com.tpp.threat_perception_platform.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
public class PermissionService {

    private static final Integer ROLE_ID = 1; // 管理员角色ID

    private final UserMapper userMapper;
    private final RoleMapper roleMapper;

    @Autowired
    public PermissionService(UserMapper userMapper, RoleMapper roleMapper) {
        this.userMapper = userMapper;
        this.roleMapper = roleMapper;
    }

    public Set<String> getCurrentUserPermissions(String userName) {
        // 1. 查询用户
        System.out.println("【权限调试】正在获取用户权限，用户名：" + userName);
        User user = userMapper.selectByUserName(userName);
        if (user == null) return Collections.emptySet();
        if (user == null) {
            System.out.println("【权限调试】未找到该用户");
            return Collections.emptySet();
        }
        // 2. 检查是否为管理员
        if (isAdmin(user.getUserRole())) {
            return getAllPermissions();
        }

        // 3. 普通用户权限
        return getNormalUserPermissions();

    }

    private boolean isAdmin(Integer roleId) {
        // 使用MyBatis的Mapper接口查询角色信息
        Role role = roleMapper.selectByPrimaryKey(roleId.longValue());
        return role != null && ROLE_ID.equals(role.getRoleId().intValue());
    }

    private Set<String> getAllPermissions() {
        return Stream.of(PermissionEnum.values())
                .map(PermissionEnum::getPermission)
                .collect(Collectors.toSet());
    }

    private Set<String> getNormalUserPermissions() {
        // 普通用户的权限集合（根据图片描述的规则）
        Set<String> permissions = new HashSet<>();
        permissions.add(PermissionEnum.HOST_SAVE.getPermission());
        permissions.add(PermissionEnum.HOST_LIST.getPermission());
        permissions.add(PermissionEnum.LOGIN_DELETE.getPermission());
        permissions.add(PermissionEnum.LOGIN_CHECK.getPermission());
        permissions.add(PermissionEnum.RABBIT_CHECK.getPermission());
        return permissions;
    }


}